package com.software.loginregister.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.software.loginregister.R;
import com.software.loginregister.adapter.NotificationAdapter;
import com.software.loginregister.api.NotificationApi;
import com.software.loginregister.entity.NotificationItem;
import com.software.loginregister.entity.Result;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class NotificationActivity extends AppCompatActivity {

    private RecyclerView rvNotifications;
    private ImageView ivBackNotification;
    private NotificationAdapter notificationAdapter;
    private SharedPreferences sharedPreferences;
    private Long userId;
    private ProgressDialog progressDialog;
    private TextView tvMarkAllRead;
    private TextView tvDeleteAll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);

        // 获取用户ID
        userId = SharedPreferencesUtil.getUserId(this);
        initViews();
        setupListeners();
        loadNotifications();
        setStatusBar();
    }

    private void initViews() {
        tvMarkAllRead = findViewById(R.id.tv_mark_all_read);
        tvDeleteAll = findViewById(R.id.tv_delete_all);
        ivBackNotification = findViewById(R.id.iv_back_notification);
        // 设置通知列表
        rvNotifications = findViewById(R.id.rv_notifications);
        // 确保设置布局管理器
        rvNotifications.setLayoutManager(new LinearLayoutManager(this));
        notificationAdapter = new NotificationAdapter();
        rvNotifications.setAdapter(notificationAdapter);

        // 添加分割线
        rvNotifications.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        // 设置可见性
        rvNotifications.setVisibility(View.VISIBLE);
        // 设置长按监听器
        notificationAdapter.setOnItemLongClickListener(this::showDeleteDialog);

        Log.d("NotificationActivity", "RecyclerView initialized");

        sharedPreferences = getSharedPreferences("notification_settings", MODE_PRIVATE);
    }

    private void setupListeners() {
        ivBackNotification.setOnClickListener(v -> finish());
        // 添加全部已读点击事件
        tvMarkAllRead.setOnClickListener(v -> {
            if (userId != null) {
                markAllAsRead();
            } else {
                Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            }
        });
        // 全部删除按钮点击事件
        tvDeleteAll.setOnClickListener(v -> {
            if (userId != null) {
                showDeleteAllDialog();
            }
        });
    }
    // 添加全部已读方法
    private void markAllAsRead() {
        showLoading();
        RetrofitClient.getInstance()
                .create(NotificationApi.class)
                .markAllNotificationsAsRead(userId)
                .enqueue(new Callback<Result<Void>>() {
                    @Override
                    public void onResponse(Call<Result<Void>> call,
                                           Response<Result<Void>> response) {
                        hideLoading();
                        if (response.isSuccessful() && response.body() != null) {
                            Result<Void> result = response.body();
                            if (result.getCode() == 1) {  // 使用你的成功响应码
                                Toast.makeText(NotificationActivity.this,
                                        "已将所有通知标记为已读", Toast.LENGTH_SHORT).show();
                                // 更新列表中所有通知的状态
                                updateAllNotificationsAsRead();
                                // 重新加载通知列表
                                loadNotifications();
                            } else {
                                Toast.makeText(NotificationActivity.this,
                                        result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Void>> call, Throwable t) {
                        hideLoading();
                        Toast.makeText(NotificationActivity.this,
                                "标记已读失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    // 更新适配器中所有通知的已读状态
    private void updateAllNotificationsAsRead() {
        List<NotificationItem> currentNotifications = notificationAdapter.getNotifications();
        if (currentNotifications != null) {
            for (NotificationItem item : currentNotifications) {
                item.setRead(true);
            }
            notificationAdapter.notifyDataSetChanged();
        }
    }
    private void loadNotifications() {
        if (userId == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        showLoading();
        Log.d("NotificationActivity", "开始加载通知");

        RetrofitClient.getInstance()
                .create(NotificationApi.class)
                .getNotifications(userId, null, false)
                .enqueue(new Callback<Result<List<NotificationItem>>>() {
                    @Override
                    public void onResponse(Call<Result<List<NotificationItem>>> call,
                                           Response<Result<List<NotificationItem>>> response) {
                        hideLoading();
                        Log.d("NotificationActivity", "收到服务器响应");

                        if (response.isSuccessful() && response.body() != null) {
                            Result<List<NotificationItem>> result = response.body();
                            Log.d("NotificationActivity", "响应码: " + result.getCode());

                            // 修改这里的判断条件，因为你的响应码是 1
                            if (result.getCode() == 1 && result.getData() != null) {
                                Log.d("NotificationActivity", "数据大小: " + result.getData().size());
                                runOnUiThread(() -> {
                                    notificationAdapter.setNotifications(result.getData());
                                    // 检查列表是否为空
                                    if (result.getData().isEmpty()) {
                                        showEmptyView();
                                    } else {
                                        hideEmptyView();
                                    }
                                });
                            } else {
                                Log.d("NotificationActivity", "响应码不是1或数据为null");
                                Toast.makeText(NotificationActivity.this,
                                        result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Log.d("NotificationActivity", "响应不成功或响应体为null");
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<List<NotificationItem>>> call, Throwable t) {
                        hideLoading();
                        Log.e("NotificationActivity", "加载失败", t);
                        Toast.makeText(NotificationActivity.this,
                                "获取通知失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }
    private void showEmptyView() {
        // 显示空视图
        View emptyView = findViewById(R.id.empty_view);
        if (emptyView != null) {
            emptyView.setVisibility(View.VISIBLE);
            rvNotifications.setVisibility(View.GONE);
        }
    }

    private void hideEmptyView() {
        // 隐藏空视图
        View emptyView = findViewById(R.id.empty_view);
        if (emptyView != null) {
            emptyView.setVisibility(View.GONE);
            rvNotifications.setVisibility(View.VISIBLE);
        }
    }
    private void markAsRead(NotificationItem item) {
        RetrofitClient.getInstance()
                .create(NotificationApi.class)  // 改用 create
                .markNotificationAsRead(item.getId(), userId)
                .enqueue(new Callback<Result<Void>>() {
                    @Override
                    public void onResponse(Call<Result<Void>> call,
                                           Response<Result<Void>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            Result<Void> result = response.body();
                            if (result.getCode() == 200) {
                                // 刷新通知列表
                                loadNotifications();
                            } else {
                                Toast.makeText(NotificationActivity.this,
                                        result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Void>> call, Throwable t) {
                        Toast.makeText(NotificationActivity.this,
                                "标记已读失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }
    private void showLoading() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("加载中...");
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }

    private void hideLoading() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
    // 显示删除单个通知的对话框
    private void showDeleteDialog(NotificationItem item) {
        new AlertDialog.Builder(this)
                .setTitle("删除通知")
                .setMessage("确定要删除这条通知吗？")
                .setPositiveButton("删除", (dialog, which) -> deleteNotification(item.getId()))
                .setNegativeButton("取消", null)
                .show();
    }

    // 显示删除所有通知的对话框
    private void showDeleteAllDialog() {
        new AlertDialog.Builder(this)
                .setTitle("删除全部通知")
                .setMessage("确定要删除所有通知吗？")
                .setPositiveButton("删除", (dialog, which) -> deleteAllNotifications())
                .setNegativeButton("取消", null)
                .show();
    }

    // 删除单个通知
    private void deleteNotification(Long notificationId) {
        RetrofitClient.getInstance()
                .create(NotificationApi.class)
                .deleteNotification(notificationId, userId)
                .enqueue(new Callback<Result<Void>>() {
                    @Override
                    public void onResponse(Call<Result<Void>> call, Response<Result<Void>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            Result<Void> result = response.body();
                            if (result.getCode() == 1) {
                                notificationAdapter.removeNotification(notificationId);
                                Toast.makeText(NotificationActivity.this,
                                        "删除成功", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Void>> call, Throwable t) {
                        Toast.makeText(NotificationActivity.this,
                                "删除失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    // 删除所有通知
    private void deleteAllNotifications() {
        RetrofitClient.getInstance()
                .create(NotificationApi.class)
                .deleteAllNotifications(userId)
                .enqueue(new Callback<Result<Void>>() {
                    @Override
                    public void onResponse(Call<Result<Void>> call, Response<Result<Void>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            Result<Void> result = response.body();
                            if (result.getCode() == 1) {
                                notificationAdapter.clearAll();
                                Toast.makeText(NotificationActivity.this,
                                        "已删除所有通知", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Void>> call, Throwable t) {
                        Toast.makeText(NotificationActivity.this,
                                "删除失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }


    private void setStatusBar() {
        Window window = getWindow();
        // 设置状态栏背景为透明
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);

        // 设置状态栏文字颜色为深色
        View decorView = window.getDecorView();
        int flags = decorView.getSystemUiVisibility();
        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        decorView.setSystemUiVisibility(flags);

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }
}
